import React, { useState, useEffect } from 'react';
import './healthmanagement.css';
import axios from 'axios';
import { BackTop } from '@nutui/nutui-react';
import { useNavigate } from 'react-router-dom';
// 部门数据
const departmentDatabase = {
  内科: [
    {
      name: '呼吸内科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门研究和治疗呼吸系统疾病'
    },
    {
      name: '心血管内科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门研究和治疗心脏和血管系统疾病'
    },
    {
      name: '消化内科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门研究和治疗消化系统疾病'
    }
  ],
  外科: [
    {
      name: '普通外科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '处理一般外科手术和治疗'
    },
    {
      name: '骨科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门研究和治疗骨骼和关节系统疾病'
    },
    {
      name: '神经外科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门进行脑部和神经系统手术治疗'
    }
  ],
  妇产科: [
    {
      name: '产科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门处理孕产相关医疗服务'
    },
    {
      name: '妇科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门研究和治疗女性疾病'
    }
  ],
  儿科: [
    {
      name: '儿童内科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门治疗儿童内科疾病'
    },
    {
      name: '儿童外科',
      positions: ['主任医师', '副主任医师', '主治医师', '住院医师'],
      description: '专门进行儿童外科手术和治疗'
    }
  ]
};

// 排班时段
const scheduleTimeSlots = [
  { id: 1, name: '早班', time: '08:00-16:00' },
  { id: 2, name: '中班', time: '16:00-24:00' },
  { id: 3, name: '夜班', time: '00:00-08:00' }
];

const HealthManagement = () => {
  const [activeTab, setActiveTab] = useState('schedule');
  const [scheduleData, setScheduleData] = useState([]);
  const [selectedDepartment, setSelectedDepartment] = useState(null);
  const [selectedSubDepartment, setSelectedSubDepartment] = useState(null);
  const [selectedPosition, setSelectedPosition] = useState('');
  const [selectedDoctor, setSelectedDoctor] = useState(null);
  const [newScheduleEntry, setNewScheduleEntry] = useState({
    doctorName: '',
    department: '',
    subDepartment: '',
    position: '',
    scheduleDate: '',
    timeSlot: '',
    notes: ''
  });

  // 添加统计数据的state
  const [statistics, setStatistics] = useState({
    departmentStats: {},
    timeSlotStats: {},
    weeklyStats: []
  });

  const [filteredSchedules, setFilteredSchedules] = useState([]);

  // 计算统计数据
  const calculateStatistics = (data) => {
    const departmentStats = {};
    const timeSlotStats = {};
    const weeklyStats = new Array(7).fill(0);

    data.forEach(schedule => {
      // 按科室统计
      if (!departmentStats[schedule.subDepartment]) {
        departmentStats[schedule.subDepartment] = {
          total: 0,
          doctors: new Set(),
          byPosition: {}
        };
      }
      departmentStats[schedule.subDepartment].total += 1;
      departmentStats[schedule.subDepartment].doctors.add(schedule.doctorName);
      if (!departmentStats[schedule.subDepartment].byPosition[schedule.position]) {
        departmentStats[schedule.subDepartment].byPosition[schedule.position] = 0;
      }
      departmentStats[schedule.subDepartment].byPosition[schedule.position] += 1;

      // 按时段统计
      if (!timeSlotStats[schedule.timeSlot]) {
        timeSlotStats[schedule.timeSlot] = 0;
      }
      timeSlotStats[schedule.timeSlot] += 1;

      // 按周统计
      const day = new Date(schedule.scheduleDate).getDay();
      weeklyStats[day]++;
    });

    setStatistics({
      departmentStats,
      timeSlotStats,
      weeklyStats
    });
  };

  // 获取排班数据
  const fetchScheduleData = async () => {
    try {
      const response = await axios.get('http://localhost:3000/have/schedule-data');
      const data = response.data.data;
      setScheduleData(data);
      calculateStatistics(data);
      setFilteredSchedules(data);
    } catch (error) {
      console.error('Error fetching schedule data:', error);
    }
  };

  // 处理排班提交
  const handleScheduleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (selectedDoctor) {
        // 更新现有排班
        await axios.post(`http://localhost:3000/have/schedule-update/${selectedDoctor._id}`, {
          ...newScheduleEntry
        });
        setSelectedDoctor(null);
      } else {
        // 添加新排班
        await axios.post('http://localhost:3000/have/schedule-add', {
          ...newScheduleEntry
        });
      }
      setNewScheduleEntry({
        doctorName: '',
        department: '',
        subDepartment: '',
        position: '',
        scheduleDate: '',
        timeSlot: '',
        notes: ''
      });
      fetchScheduleData();
    } catch (error) {
      console.error('Error submitting schedule data:', error);
    }
  };

  // 处理医生选择
  const handleDoctorSelect = (doctor) => {
    setSelectedDoctor(doctor);
    setNewScheduleEntry({
      doctorName: doctor.doctorName,
      department: doctor.department,
      subDepartment: doctor.subDepartment,
      position: doctor.position,
      scheduleDate: doctor.scheduleDate,
      timeSlot: doctor.timeSlot,
      notes: doctor.notes || ''
    });
  };

  // 处理科室选择
  const handleDepartmentSelect = (department) => {
    if (selectedDepartment === department) {
      // 如果点击已选中的科室，则取消选择
      setSelectedDepartment(null);
      setSelectedSubDepartment(null);
      setSelectedPosition(null);
      setFilteredSchedules(scheduleData);
    } else {
      setSelectedDepartment(department);
      setSelectedSubDepartment(null);
      setSelectedPosition(null);
      // 过滤对应科室的排班数据
      const filtered = scheduleData.filter(schedule => schedule.department === department);
      setFilteredSchedules(filtered);
    }
  };

  // 处理子科室选择
  const handleSubDepartmentSelect = (subDepartment) => {
    if (selectedSubDepartment === subDepartment) {
      // 如果点击已选中的子科室，则取消选择
      setSelectedSubDepartment(null);
      setSelectedPosition(null);
      const filtered = scheduleData.filter(schedule => schedule.department === selectedDepartment);
      setFilteredSchedules(filtered);
    } else {
      setSelectedSubDepartment(subDepartment);
      setSelectedPosition(null);
      // 更新表单中的科室和子科室信息
      setNewScheduleEntry({
        ...newScheduleEntry,
        department: selectedDepartment,
        subDepartment: subDepartment,
        position: ''  // 清空职位选择
      });
      // 过滤对应子科室的排班数据
      const filtered = scheduleData.filter(schedule => 
        schedule.department === selectedDepartment && 
        schedule.subDepartment === subDepartment
      );
      setFilteredSchedules(filtered);
    }
  };

  const handlePositionSelect = (position) => {
    if (selectedPosition === position) {
      // 如果点击已选中的职位，则取消选择
      setSelectedPosition(null);
      const filtered = scheduleData.filter(schedule => 
        schedule.department === selectedDepartment && 
        schedule.subDepartment === selectedSubDepartment
      );
      setFilteredSchedules(filtered);
    } else {
      setSelectedPosition(position);
      // 过滤对应职位的排班数据
      const filtered = scheduleData.filter(schedule => 
        schedule.department === selectedDepartment && 
        schedule.subDepartment === selectedSubDepartment && 
        schedule.position === position
      );
      setFilteredSchedules(filtered);
    }
  };

  const navigate = useNavigate();
  useEffect(() => {
    fetchScheduleData();
  }, []);

  return (
    <div className="health-management">
      <div className="health-header">
        <h2 style={{color:'rgba(0, 136, 220,0.7)',textAlign:'center'}} onClick={()=>{
          navigate('/forWork')
        }}>我的排班管理</h2>
        <div className="tab-buttons">
          <button 
            className={activeTab === 'schedule' ? 'active' : ''} 
            onClick={() => setActiveTab('schedule')}
          >
            排班记录
          </button>
          <button 
            className={activeTab === 'stats' ? 'active' : ''} 
            onClick={() => setActiveTab('stats')}
          >
            统计信息
          </button>
        </div>
      </div>

      {activeTab === 'schedule' ? (
        <div className="schedule-section">
          <div className="schedule-content">
            <div className="schedule-left">
              <div className="department-selection">
                <h3>选择科室</h3>
                <div className="department-list">
                  {Object.entries(departmentDatabase).map(([dept, deptData]) => (
                    <div 
                      key={dept} 
                      className={`department-group ${selectedDepartment === dept ? 'active' : ''}`}
                    >
                      <div 
                        className={`department-main ${selectedDepartment === dept ? 'expanded' : ''}`}
                        onClick={() => handleDepartmentSelect(dept)}
                      >
                        {dept}
                      </div>
                      <div className={`subdepartment-list ${selectedDepartment === dept ? 'visible' : ''}`}>
                        {deptData.map((subDept) => (
                          <div 
                            key={subDept.name}
                            className={`subdepartment-item ${selectedSubDepartment === subDept.name ? 'active' : ''}`}
                            onClick={() => handleSubDepartmentSelect(subDept.name)}
                          >
                            {subDept.name}
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="schedule-right">
              <div className="schedule-form">
                <h3>{selectedDoctor ? '修改排班' : '添加排班'}</h3>
                {(selectedDepartment || selectedSubDepartment) && (
                  <div className="selected-department-info">
                    <p>
                      {selectedDepartment && `${selectedDepartment} `}
                      {selectedSubDepartment && `> ${selectedSubDepartment}`}
                    </p>
                  </div>
                )}
                <form onSubmit={handleScheduleSubmit}>
                  <div className="form-group">
                    <input
                      type="text"
                      value={newScheduleEntry.doctorName}
                      onChange={(e) => setNewScheduleEntry({...newScheduleEntry, doctorName: e.target.value})}
                      placeholder="医生姓名"
                      required
                    />
                    {selectedSubDepartment && (
                      <select
                        value={newScheduleEntry.position}
                        onChange={(e) => setNewScheduleEntry({...newScheduleEntry, position: e.target.value})}
                        required
                      >
                        <option value="">选择职位</option>
                        {departmentDatabase[selectedDepartment]
                          ?.find(d => d.name === selectedSubDepartment)
                          ?.positions.map(pos => (
                            <option key={pos} value={pos}>{pos}</option>
                          ))}
                      </select>
                    )}
                    <input
                      type="date"
                      value={newScheduleEntry.scheduleDate}
                      onChange={(e) => setNewScheduleEntry({...newScheduleEntry, scheduleDate: e.target.value})}
                      required
                    />
                    <select
                      value={newScheduleEntry.timeSlot}
                      onChange={(e) => setNewScheduleEntry({...newScheduleEntry, timeSlot: e.target.value})}
                      required
                    >
                      <option value="">选择时段</option>
                      {scheduleTimeSlots.map(slot => (
                        <option key={slot.id} value={slot.name}>{slot.name} ({slot.time})</option>
                      ))}
                    </select>
                    <textarea
                      value={newScheduleEntry.notes}
                      onChange={(e) => setNewScheduleEntry({...newScheduleEntry, notes: e.target.value})}
                      placeholder="备注"
                    />
                    <button 
                      type="submit" 
                      className={selectedDoctor ? 'update-button' : 'add-button'}
                      disabled={!selectedSubDepartment}
                    >
                      {selectedDoctor ? '修改' : '添加'}
                    </button>
                    {selectedDoctor && (
                      <button 
                        type="button"
                        className="cancel-button"
                        onClick={() => {
                          setSelectedDoctor(null);
                          setNewScheduleEntry({
                            doctorName: '',
                            department: selectedDepartment || '',
                            subDepartment: selectedSubDepartment || '',
                            position: '',
                            scheduleDate: '',
                            timeSlot: '',
                            notes: ''
                          });
                        }}
                      >
                        取消修改
                      </button>
                    )}
                  </div>
                </form>
              </div>

              <div className="schedule-list">
                <h3>排班记录</h3>
                <div className="schedule-table">
                  <table>
                    <thead>
                      <tr>
                        <th>科室</th>
                        <th>子科室</th>
                        <th>医生</th>
                        <th>职位</th>
                        <th>日期</th>
                        <th>时段</th>
                        <th>备注</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredSchedules.length > 0 ? (
                        filteredSchedules.map((schedule, index) => (
                          <tr key={index} onClick={() => handleDoctorSelect(schedule)}>
                            <td>{schedule.department || '-'}</td>
                            <td>{schedule.subDepartment || '-'}</td>
                            <td>{schedule.doctorName || '-'}</td>
                            <td>{schedule.position || '-'}</td>
                            <td>{schedule.scheduleDate ? new Date(schedule.scheduleDate).toLocaleDateString('zh-CN') : '-'}</td>
                            <td>{schedule.timeSlot || '-'}</td>
                            <td>{schedule.notes || '-'}</td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td colSpan="7" className="no-data">暂无排班记录</td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="statistics-section">
          <div className="stats-container">
            <div className="stats-card department-stats">
              <h3>科室排班统计</h3>
              <div className="stats-content">
                {Object.entries(statistics.departmentStats).map(([dept, stats]) => (
                  <div key={dept} className="department-stat-item">
                    <h4>{dept}</h4>
                    <p>总排班数: {stats.total}</p>
                    <p>医生人数: {stats.doctors.size}</p>
                    <div className="position-stats">
                      {Object.entries(stats.byPosition).map(([position, count]) => (
                        <p key={position}>{position}: {count}次</p>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="stats-card time-stats">
              <h3>时段统计</h3>
              <div className="stats-content">
                {Object.entries(statistics.timeSlotStats).map(([slot, count]) => (
                  <div key={slot} className="time-stat-item">
                    <span>{slot}:</span>
                    <span>{count}次排班</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="stats-card weekly-stats">
              <h3>每周排班分布</h3>
              <div className="stats-content">
                {['周日', '周一', '周二', '周三', '周四', '周五', '周六'].map((day, index) => (
                  <div key={day} className="weekly-stat-item">
                    <span>{day}:</span>
                    <span>{statistics.weeklyStats[index]}次排班</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="stats-card schedule-details">
              <h3>排班详细记录</h3>
              <div className="schedule-table">
                <table>
                  <thead>
                    <tr>
                      <th>医生姓名</th>
                      <th>科室</th>
                      <th>职位</th>
                      <th>日期</th>
                      <th>时段</th>
                      <th>备注</th>
                    </tr>
                  </thead>
                  <tbody>
                    {scheduleData.map(schedule => (
                      <tr key={schedule._id}>
                        <td>{schedule.doctorName}</td>
                        <td>{schedule.subDepartment}</td>
                        <td>{schedule.position}</td>
                        <td>{new Date(schedule.scheduleDate).toLocaleDateString()}</td>
                        <td>{schedule.timeSlot}</td>
                        <td>{schedule.notes || '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      )}

      <BackTop />
    </div>
  );
};

export default HealthManagement;